
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.common import exceptions

import json

def create_chrome_driver(headless=False):
    options=webdriver.ChromeOptions()
    if headless:
        options.add_argument('--headless')

    #去掉chrome正在受到测试软件的控制的提示条
    options.add_experimental_option('excludeSwitches',['enable-automation'])
    options.add_experimental_option('useAutomationExtension',False)
    options.add_argument("--disable-blink-features=AutomationControlled")
    
    # 定义chrome驱动去地址
    service =  Service('chromedriver.exe')
    # service=Service(r'E:\项目区\项目2023-编程项目教程\ssq_caipiao_pachong\taobaoSpider\chromedriver.exe')

    browser=webdriver.Chrome(service=service,options=options)
    #反爬，修改为navigator.webdriver=undefined
    browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
        'source':'Object.defineProperty(navigator,"webdriver",{get:()=>undefined})'})

    return browser

def add_cookies(browser,cookie_file):
    with open(cookie_file,'r') as file:
        cookies_list=json.load(file)
        for cookie_dict in cookies_list:
            if cookie_dict['secure']:
                try:
                    browser.add_cookie(cookie_dict)
                except exceptions.InvalidCookieDomainException as e:
                    print(e.msg)
                

def test():
    print("ggggggg")